package com.qianfeng.libra.cowshop.app.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Set;

/**
 * Created by Libra丶ZW on 2014/12/30 0030.
 */

//HTTP 网络请求的工具类，包含了，GET，POST，PUT，DELETE
//这4种请求方法的支持
public class HttpTools {
    /**
     * GET 请求
     * @param url 请求的网址
     * @return byte[] 网络数据字节数组
     */
    public static  byte[] get(String url){
        byte[] ret = null;
        if (url != null) {
            HttpGet request = new HttpGet(url);
            ret = processEmptyRequest(request);
        }
        return ret;
    }
    /**
     * Delete 请求
      * @param url 请求的网址
     * @return byte[] 网络数据字节数组
     */
    public static  byte[] delete(String url){
        byte[] ret = null;
        if (url != null) {
            HttpDelete request = new HttpDelete(url);
            ret = processEmptyRequest(request);
        }
        return ret;
    }
    private static byte[] processEmptyRequest(HttpRequestBase request){
        byte[] ret = null;
        HttpClient httpClient = new DefaultHttpClient();
        try {
            HttpResponse httpResponse = httpClient.execute(request);
            if(httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = httpResponse.getEntity();
                ret = EntityUtils.toByteArray(entity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            httpClient.getConnectionManager().shutdown();
        }
        return ret;
    }


    /**
     * POST 请求
     * post 请求要提交数据，提交数据的方式
     * 本方法采用 提交 key=value&key=value的形式
     * 这种数据格式就是网页中，form表单提交的数据格式
     * @param url 请求的网址
     * @param  params   HashMap 包含参数，也就是key=value的集合
     * @return byte[] 网络数据字节数组
     */
    public static  byte[] post(String url,HashMap<String,String> params){
        return post(url,params,"UTF-8");
    }
    /**
     * POST 请求
     * post 请求要提交数据，提交数据的方式
     * 本方法采用 提交 key=value&key=value的形式
     * 这种数据格式就是网页中，form表单提交的数据格式
     * @param url 请求的网址
     * @param  params   HashMap 包含参数，也就是key=value的集合
     * @param encoding 编码方式
     * @return byte[] 网络数据字节数组
     */
    public static  byte[] post(String url,HashMap<String,String> params,String encoding){
        byte[] ret = null;
        if (url != null) {
            HttpPost request = new HttpPost(url);
            ret = processEntityRequest(request,params,encoding);
        }
        return ret;
    }
    public  static  byte[] put(String url ,HashMap<String,String> params ,String encoding){
        byte[] ret = null;
        if (url != null) {
            HttpPut request = new HttpPut(url);
            ret = processEntityRequest(request,params,encoding);
        }
        return ret;
    }
    private static byte[] processEntityRequest(
            HttpEntityEnclosingRequestBase request,HashMap<String,String> params,String encoding){
        byte[] ret = null;
        if (params != null) {
            try {
                //setEntity 用于提交设置的数据
                //对于key=value&key=value的形式，需要使用UrlEncodedFormEntity
                LinkedList<NameValuePair> parameters = new LinkedList<NameValuePair>();
                //获取HashMap中的key集合
                Set<String> keySet = params.keySet();
                for (String key : keySet) {
                    String value = params.get(key);
                    parameters.add(new BasicNameValuePair(key,value));
                }
                //将parameters中的key-value 通过UrlEncodedFormEntity进行组合
                //形成 key=value 的形式（这种形式是服务器标准数据提交的格式）
                if (encoding == null) {
                    encoding = "UTF-8";
                }
                UrlEncodedFormEntity entity
                        = new UrlEncodedFormEntity(parameters, encoding);//必须使用2个参数的构造方法
                request.setEntity(entity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        HttpClient httpClient = new DefaultHttpClient();
        try {
            HttpResponse httpResponse = httpClient.execute(request);
            if(httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = httpResponse.getEntity();
                ret = EntityUtils.toByteArray(entity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            httpClient.getConnectionManager().shutdown();
        }
        return ret;
    }

}
